package quanlyhochieu.truyvanhinhanhtheothongtincanhan;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.faces.model.SelectItem;

import dbutil.ConnectDB;

import quanlydoanra.baocao.dinhky.Year;
import quanlyhochieu.truyvanhinhanh.Table;
import utils.DateUtils;
import utils.UtilsOnScopes;

public class BeanTruyVan {
	
	private String hoTen="";
	private String sohochieu="";
	private String namsinh;
	private String error;
	private String path ="/qlhochieu/truyvanhinhanhtheothongtincanhan/emptyBieuMau.xhtml" ;
	private List<Table> list;
	
	
	private boolean checkInput(){
		boolean result = true;
		if(this.hoTen.equals("") && this.sohochieu.equals("") && this.namsinh.equals("-1")){
			this.setError("Bạn phải nhập 1 trong 3 thông tin ở bên dưới <br/> hoặc có thể nhập tất cả !");
			return result = false;
		}
		return result;
	}

	public String getHoTen() {
		return hoTen;
	}

	public void setHoTen(String hoTen) {
		this.hoTen = hoTen;
	}

	public String getSohochieu() {
		return sohochieu;
	}

	public void setSohochieu(String sohochieu) {
		this.sohochieu = sohochieu;
	}

	public String getNamsinh() {
		return namsinh;
	}

	public void setNamsinh(String namsinh) {
		this.namsinh = namsinh;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public List<Table> getList() {
		return list;
	}

	public void setList(List<Table> list) {
		this.list = list;
	}
	
	
	/**************************************
	 * Method name		: viewImage
	 * Return type		: String
	 * Description		:Truy van lay len hinh anh
	 * Created date		: Aug 16, 2008
	 * Author			: Honglk
	 **************************************/
	public  String viewImage() throws IOException {
		ConnectDB.connectDB();
		this.setError("");
		this.delete();
		if(this.checkInput() == false){
			return "";
		}else
		{
		this.searchFromInfoPerson(this.hoTen, this.namsinh,this.sohochieu);
		}
		return "okBeanTruyVanAnhTheoThongTin";
	}
	
	
	/**************************************
	 * Method name		: searchFromInfoPerson
	 * Return type		: void
	 * Description		:Tim kiem theo thong tin: Ho Ten,Nam Sinh
	 * Created date		: Aug 17, 2008
	 * Author			: Honglk
	 **************************************/
	public void searchFromInfoPerson(String hoten, String namsinh,String sohc) {
		List<Table> list = new ArrayList<Table>();
		byte[] arrData = new byte[10024];
		String SQL = "SELECT DISTINCT A.namsinh,A.ten, A.gioitinh,A.dangvien,A.chucvu,A.cmnd,A.anh" +
				" FROM canhan A inner join hochieu B on A.cmnd = B.cmnd " + " WHERE "
				+ this.searchHelp(hoten, namsinh,sohc);
		System.out.println(SQL);
		try {
			ResultSet resultSet = ConnectDB.statement.executeQuery(SQL);
			String realPath = UtilsOnScopes
					.getSession()
					.getServletContext()
					.getRealPath(
							"qlhochieu/truyvanhinhanhtheothongtincanhan/image/");
			int canRead = 0;
			String cmnd = "";
			int stt = 0;

			while (resultSet.next()) {
				stt = stt + 1;
				String ten = resultSet.getString("ten");
				String namsinhTemp = resultSet.getString("namsinh") == null ? ""
										: resultSet.getString("namsinh");
				String gioitinh = resultSet.getBoolean("gioitinh") == true ? "Nam"
						: "Nữ";
				// String coquan = "Cơ quan :"+resultSet.getString("coquan");
				String dangvien = resultSet.getBoolean("dangvien") == true ? "Đảng viên"
						: "Không";
				String chucvu = "<b> Chức vụ: </b> "
						+ resultSet.getString("chucvu");
				cmnd = resultSet.getString("cmnd");
				
				Table table = new Table();
				File fileImage = new File(realPath + "/" + cmnd + ".jpg");
				FileOutputStream fos = null;
				try {
					fos = new FileOutputStream(fileImage);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				BufferedOutputStream bos = new BufferedOutputStream(fos);
				BufferedInputStream bis = null;
				bis = new BufferedInputStream(resultSet.getBinaryStream("anh"));
				System.out.println("duong dan :" + realPath);
				try {
					while ((canRead = bis.read(arrData)) != -1) {
						bos.write(arrData, 0, canRead);
					}
					bos.flush();
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				String infoPassport = this.getInfoPassport(cmnd);
				String info = "<table style='font-size:9pt' border='0' align='right'>"
						+ "<tr><td> <li><b>Họ tên: "
						+ ten
						+ "</b></li> </td></tr>"
						+ "<p/>"
						+ "<tr><td><li>"
						+ "<b> Năm sinh: </b>"+namsinhTemp
						+ "</li></td></tr>"
						+ "<p/>"
						+ "<tr><td><li> <b>Số CMND:</b> "
						+ cmnd
						+ "</li></td></tr>"
						+ "<p/>"
						+ "<tr><td><li><b> Giới tính:</b> "
						+ gioitinh
						+ "</li></td></tr>"
						+ "<p/>"
						+ "<tr><td><li>"
						+ chucvu
						+ "</li></td></tr>"
						+ "<p/>"
						+ "<tr><td><li><b>Đảng viên:</b> "
						+ dangvien
						+ "</li></td></tr>" + infoPassport + "</table>";
				table.setInfo(info);
				table.setPathImage("image/" + cmnd + ".jpg");
				System.out.println("duong dan image:" + table.getPathImage());
				System.out.println("duong info:" + table.getInfo());
				table.setStt(String.valueOf(stt));
				list.add(table);
			}
			this.setList(list);
			if(this.getList() != null && this.getList().size()> 0){
				this.setPath("/qlhochieu/truyvanhinhanhtheothongtincanhan/bieumau.xhtml");
			}else {
				this.setError("Không có dữ liệu !");
				return;
			}
		} catch (SQLException se) {
			se.printStackTrace();
			System.out.println(" SQL is invalid");
		}
	}
	
	/***************************************************************************
	 * Method name : searchHelp 
	 * Return type : String 
	 * Decription :Hỗ trợ cho hàm
	 * search Created date : Jun 6, 2008 
	 * Author : Honglk
	 **************************************************************************/
	public String searchHelp(String hoten, String namsinh,String sohc) {
		StringBuffer buffer = new StringBuffer();
		String strTemp = "";
		String strTempCond2 = "namsinh = '" + namsinh + "' OR '"
		+ (namsinh.equals("-1") ? "0" : namsinh) + "'= '0'";
		String strTempCond3 = "TRIM(LOWER(ten)) LIKE TRIM(LOWER('%"
				+ hoten.trim()	 + "%')) OR '"
				+ (hoten.equals("") ? "1" : hoten.trim()) + "'='1'";
        String strTempCond1 = "TRIM(LOWER(sohc)) LIKE TRIM(LOWER('%"
			+ sohc + "%')) OR '"
			+ (sohc.equals("") ? "1" : sohc) + "'='1'";
        
		strTemp = "(" + strTempCond2 + ") AND (" + strTempCond3 + ") AND (" +strTempCond1+ ")";
				
		buffer.append("(");
		buffer.append(strTemp);
		buffer.append(")");
		return buffer.toString();
	}
	
	/**************************************
	 * Method name		: getInfoPassport
	 * Return type		: String
	 * Description		:lay ra danh sach HC tuong ung voi nguoi
	 * Created date		: Aug 16, 2008
	 * Author			: Honglk
	 **************************************/
//	public String getInfoPassport(String cmnd) {
//		ConnectDB.connectDB();
//		StringBuffer buffer = new StringBuffer();
//		String SQL = "SELECT * FROM hochieu hc WHERE hc.cmnd ='" + cmnd + "'";
//		try{
//		ResultSet resultSet = ConnectDB.statement.executeQuery(SQL);
//		while (resultSet.next()) {
//		String loaiHC = resultSet.getString("loaihc").toString();
//		buffer.append("<tr><td><li><b>Số HC:</b> "+loaiHC+"</li></td></tr><p/>");
//		}
//		}catch(Exception e){
//			
//		}
//		return buffer.toString();
//	}
	
	public String getInfoPassport(String cmnd) {
		ConnectDB.connectDB();
		String SQL = "SELECT * FROM hochieu hc WHERE hc.cmnd ='" + cmnd + "'";
		System.out.println(SQL);
		ArrayList<HashMap<String, Object>> array = ConnectDB
				.getDataTypeList(SQL);
		StringBuffer buffer = new StringBuffer();
		try {
			if (array.size() > 0) {
				HashMap<String, Object> hash = new HashMap<String, Object>();
				for (int i = 0; i < array.size(); i++) {
					hash = (HashMap<String, Object>) array.get(i);
					String loaiHC = hash.get("loaihc").toString();
					String soHC = hash.get("sohc").toString();
					String ngaycap = DateUtils.formatDate(hash.get("ngaycap").toString());
					String ngayhethan = DateUtils.formatDate(hash.get("ngayhethan").toString());
					String noicap = hash.get("noicap").toString();
					
					buffer.append("<tr><td><li><b>Số HC:</b> "+soHC+"</li></td></tr><p/>");
					buffer.append("<tr><td><li><b>Loại HC:</b>" +loaiHC+"</li></td></tr><p/>");
					buffer.append("<tr><td><li><b>Nơi cấp:</b> "+noicap+"</li></td></tr><p/>");
					buffer.append("<tr><td><li><b>Ngày cấp:</b> "+ngaycap+"</li></td></tr><p/>");
					buffer.append("<tr><td><li><b>Ngày hết hạn:</b> "+ngayhethan+"</li></td></tr><p/>");
				}
			}
		} catch (Exception e) {

		}
		return buffer.toString();
	}
//	
	/**************************************
	 * Method name		: searchNumberPassport
	 * Return type		: String
	 * Description		:tim kiem theo: so ho chieu
	 * Created date		: Aug 16, 2008
	 * Author			: Honglk
	 **************************************/
	
	public void searchNumberPassport(String sohc) {
		List<Table> list = new ArrayList<Table>();
		byte[] arrData = new byte[10024];
		String SQL = "SELECT * FROM hochieu A  INNER JOIN canhan B ON  A.cmnd = B.cmnd" +
	     " WHERE TRIM(LOWER(A.sohc)) LIKE TRIM(LOWER('%" + sohc
	     + "%')) OR '" + (sohc.equals("") ? "1" : sohc)+ "'='1'";
		System.out.println(SQL);
		try {
			ResultSet resultSet = ConnectDB.statement.executeQuery(SQL);
			String realPath = UtilsOnScopes
					.getSession()
					.getServletContext()
					.getRealPath(
							"qlhochieu/truyvanhinhanhtheothongtincanhan/image/");
			int canRead = 0;
			String cmnd = "";
			int stt = 0;

			while (resultSet.next()) {
				stt = stt + 1;
				String ten = resultSet.getString("ten");
				String namsinhTemp = "<b> Năm sinh: </b> "
						+ resultSet.getString("namsinh") == null ? ""
										: resultSet.getString("namsinh");
				String gioitinh = resultSet.getBoolean("gioitinh") == true ? "Nam"
						: "Nữ";
				// String coquan = "Cơ quan :"+resultSet.getString("coquan");
				String dangvien = resultSet.getBoolean("dangvien") == true ? "Đảng viên"
						: "Không";
				String chucvu = "<b> Chức vụ: </b> "
						+ resultSet.getString("chucvu");
				String loaiHC = resultSet.getString("loaihc").toString();
				String soHC = resultSet.getString("sohc").toString();
				String ngaycap = DateUtils.formatDate(resultSet.getString("ngaycap").toString());
				String ngayhethan = DateUtils.formatDate(resultSet.getString("ngayhethan").toString());
				String noicap = resultSet.getString("noicap").toString();
				cmnd = resultSet.getString("cmnd");
				String infoPassport = this.getInfoPassport(resultSet
						.getString("cmnd"));
				Table table = new Table();
				File fileImage = new File(realPath + "/" + cmnd + ".jpg");
				FileOutputStream fos = null;
				try {
					fos = new FileOutputStream(fileImage);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				BufferedOutputStream bos = new BufferedOutputStream(fos);
				BufferedInputStream bis = null;
				bis = new BufferedInputStream(resultSet.getBinaryStream("anh"));
				System.out.println("duong dan :" + realPath);

				try {
					while ((canRead = bis.read(arrData)) != -1) {
						bos.write(arrData, 0, canRead);
					}
					bos.flush();
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				String info = "<table style='font-size:9pt' border='0' align='right'>"
						+ "<tr><td> <li><b>Họ tên: "
						+ ten
						+ "</b></li> </td></tr>"
						+ "<p/>"
						+ "<tr><td><li>"
						+ namsinhTemp
						+ "</li></td></tr>"
						+ "<p/>"
						+ "<tr><td><li> <b>Số CMND:</b> "
						+ cmnd
						+ "</li></td></tr>"
						+ "<p/>"
						+ "<tr><td><li><b> Giới tính:</b> "
						+ gioitinh
						+ "</li></td></tr>"
						+ "<p/>"
						+ "<tr><td><li>"
						+ chucvu
						+ "</li></td></tr>"
						+ "<p/>"
						+ "<tr><td><li><b>Đảng viên:</b> "
						+ dangvien
						+ "</li></td></tr>"   
						+"<p/>" 
						+"<tr><td><li><b>Số HC:</b> "+soHC+"</li></td></tr>" 
						+"<p/>"
						+"<tr><td><li><b>Loại HC:</b>" +loaiHC+"</li></td></tr>" 
						+"<p/>"
						+"<tr><td><li><b>Nơi cấp:</b> "+noicap+"</li></td></tr>" 
						+"<p/>"
						+"<tr><td><li><b>Ngày cấp:</b> "+ngaycap+"</li></td></tr>"
						+"<p/>"
						+"<tr><td><li><b>Ngày hết hạn:</b> "+ngayhethan+"</li></td></tr>" 
						+"</table>";
				table.setInfo(info);
				table.setPathImage("image/" + cmnd + ".jpg");
				System.out.println("duong dan image:" + table.getPathImage());
				System.out.println("duong info:" + table.getInfo());
				table.setStt(String.valueOf(stt));
				list.add(table);
			}
			this.setList(list);
			if(this.getList() != null && this.getList().size()> 0){
				this.setPath("/qlhochieu/truyvanhinhanhtheothongtincanhan/bieumau.xhtml");
			}else {
				this.setError("Không có dữ liệu !");
				return;
			}
		} catch (SQLException se) {
			se.printStackTrace();
			System.out.println(" SQL is invalid");
		}
	}
	
	
	
	/**************************************
	 * Method name		: reset
	 * Return type		: String
	 * Description		:
	 * Created date		: Aug 16, 2008
	 * Author			: Honglk
	 **************************************/
	public String reset() {
		this.delete();
		UtilsOnScopes.getSession().removeAttribute("beanTruyVan");
		return "okBeanTruyVanAnhTheoThongTin";
	}
	
	
	/**************************************
	 * Method name		: delete
	 * Return type		: void
	 * Description		:xoa file hinh cu
	 * Created date		: Jul 27, 2008
	 * Author			: Honglk
	 **************************************/
	public void delete() {
		 String realPath = UtilsOnScopes.getSession().getServletContext().getRealPath("qlhochieu/truyvanhinhanhtheothongtincanhan/image/");
		try {
			File file = new File(realPath);
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (File file2 : files) {
					if (file2.isFile()) {
						System.out.println(file2.delete());
						file2.delete();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**************************************
	 * Method name		: getYear
	 * Return type		: List<Year>
	 * Decription		:Lay ra danh sach cac nam
	 * Created date		: Jul 13, 2008
	 * Author			: Honglk
	 **************************************/
	private List<Year> getYear(){
		List<Year> list = new ArrayList<Year>();
		int beginYear = DateUtils.LayNamHienTai() - 18;
		int yearCurr = DateUtils.LayNamHienTai() - 80;
		while (beginYear  >= yearCurr){
			Year year = new Year();
			year.setValue(String.valueOf(beginYear));
			year.setLable(String.valueOf(beginYear));
			list.add(year);
			beginYear -=1;
		}
		return list;
	}
	
	/**************************************
	 * Method name		: listItemYear
	 * Return type		: SelectItem[]
	 * Decription		:Lay ra cac item select cua nam 
	 * Created date		: Jul 13, 2008
	 * Author			: Honglk
	 **************************************/
	public SelectItem[] listItemYear() {
		List<Year> li = this.getYear();
		SelectItem[] arrItem = new SelectItem[li.size() + 1];
		arrItem[0] = new SelectItem("-1", "---Tất cả---");
		for (int i = 0; i < li.size(); i++) {
			Year year = li.get(i);
			arrItem[i + 1] = new SelectItem(year.getValue(), year.getLable());
		}
		return arrItem;
	}
	public SelectItem[] getListItemYear() {
		return this.listItemYear();
	}
public static void main(String[] args) {
	BeanTruyVan a = new BeanTruyVan();
	System.out.println(a.getInfoPassport("10000046"));
}
}
